package com.task.poker.card.services;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Poker Sender class.
 * @author	JiDong
 * @create	November 14.2019
 *
 */
public class PokerSender implements Runnable {

    private PockerDeck pockerDeck;
    private CountDownLatch countDownLatch;
    private List<String> cards;
    private static Integer number = 0;

    public PokerSender(List<String> cards, PockerDeck pockerDeck, CountDownLatch countDownLatch) {
        this.cards = cards;
        this.pockerDeck = pockerDeck;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        // locker
        Lock locker = pockerDeck.getLocker();
        // sender
        Condition sender = pockerDeck.getSender();
        // receiver
        Condition receiver = pockerDeck.getReceiver();

        locker.lock();
        try {
            int i = 1;

            for (String card : cards) {
                if (PockerDeck.stop) {
                    break;
                }

                if (pockerDeck.getPlayerMap().size() == 3) {
                    try {
                        receiver.signal();
                        sender.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (i == 1) {
                    pockerDeck.getPlayerMap().put("player1", card);
                } else if (i == 2) {
                    pockerDeck.getPlayerMap().put("player2", card);
                } else if (i == 3) {
                    pockerDeck.getPlayerMap().put("player3", card);
                }


                i++;
                if (i == 4) {
                    i = 1;

                    synchronized (number) {
                        number++;
                    }
                }
            }

            PockerDeck.stop = true;
            System.out.println(Thread.currentThread().getName()+ " countDown sender stop:"+ PockerDeck.stop);
            countDownLatch.countDown();
        } finally {
            locker.unlock();
        }
    }

    public static int getNumber() {
        return number;
    }

}
